import { firstValueFrom } from 'rxjs';
import { filter } from 'rxjs/operators';
import { RouteLocationNormalized, Router } from 'vue-router';
import router from './index';
import { routeInfo } from './info';
import { ROUTE_404 } from './route-name';

/**
 * 守卫：权限验证
 * @param to
 * @param from
 */
export async function authRouterGuard(
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
): Promise<string | boolean> {
  console.log(`[route] from ${from.fullPath} to ${to.fullPath}`);
  checkRouteName(to, router);
  // 直接跳转型
  if (
    to.fullPath === '/403' ||
    to.fullPath === '/404' ||
    to.fullPath === '/login' ||
    to.fullPath.startsWith('/user') ||
    to.fullPath.startsWith('/answer')
  ) {
    return true;
  }

  // 等待获取登录状态
  let loginState = routeInfo.loginState;
  if (loginState === null) {
    console.log('[route] Waiting for check login state');
    loginState = await firstValueFrom(
      routeInfo.loginState$.pipe(filter((value) => value !== null)),
    );
    console.log('[route] Get login state: ', loginState);
  }

  // 检查权限
  if (loginState === true) {
    // 首页跳转
    if (to.fullPath === '/') {
      return '/manage';
    }

    return true;
  } else {
    if (to.meta.requiresAuth) {
      return '/403';
    }
  }

  // 未登录时全部跳转登录页
  return '/login';
}

/**
 *
 * @param guard
 * @param router
 * @returns
 */
export function checkRouteName(
  guard: RouteLocationNormalized,
  router: Router,
): undefined {
  if (guard.name === undefined || guard.name === null) {
    router.push({ name: ROUTE_404 });
    return;
  }
  if (!router.hasRoute(guard.name)) {
    router.push({ name: ROUTE_404 });
    return;
  }
}
